﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;

namespace NetfractionHub.Security
{
    public class Role
    {
        private byte _roleId;

        private Role()
        {
            this.Permissions = new Dictionary<Type, AccessState>();
        }
        
        /*public static Role LoadRole(XPathNavigator roleElem)
        {
            Role loadedRole = new Role();

            loadedRole._roleId = Convert.ToByte(roleElem.SelectSingleNode("@id").Value);
            loadedRole._name = roleElem.SelectSingleNode("Name").Value;
            loadedRole._ancestor = RoleManager.GetRoleById(Convert.ToByte(roleElem.SelectSingleNode("@ancestorId").Value));

            foreach (XPathNavigator node in roleElem.SelectSingleNode("SecurityPermissions").SelectChildren(XPathNodeType.Element))
            {
                loadedRole._permissions.Add((AccessPermissionBase)Enum.Parse(typeof(AccessPermissionBase), node.SelectSingleNode("@name").Value, true),
                                            (AccessState)Enum.Parse(typeof(AccessState), node.SelectSingleNode("@access").Value, true));
            }

            return loadedRole;
        }*/

        public static Role LoadRole(Community.CsharpSqlite.SQLiteClient.SqliteDataReader sdr)
        {
            Role loadedRole = new Role();

            try
            {
                loadedRole._roleId = Convert.ToByte(sdr.GetInt32(0));
                loadedRole.Name = sdr.GetString(1);
                loadedRole.Ancestor = RoleManager.GetRoleById(Convert.ToByte(sdr.GetInt32(2)));

                loadedRole.Permissions = RoleManager.GetRolePermissionsByRoleId(loadedRole._roleId);
            }
            catch (InvalidCastException ice)
            {
                Console.WriteLine(ice.Message);
                loadedRole = null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                loadedRole = null;
            }
            return loadedRole;
        }

        public byte RoleId
        {
            get { return _roleId; }
            set { _roleId = value; }
        }

        public string Name { get; set; }

        public Role Ancestor { get; set; }

        public Dictionary<Type, AccessState> Permissions { get; set; }

        public string ListPermissions()
        {
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<Type, AccessState> perm in this.Permissions)
            {
                sb.AppendLine(String.Format("Permission Name: {0}, Access: {1}", perm.Key.FullName, perm.Value));
            }
            return sb.ToString();
        }
    }
}
